package com.example.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.dao.ImagesDao;
import com.example.dto.*;
import com.example.entity.ImagesEntity;
import com.example.entity.RawMaterialsConfigEntity;
import com.example.entity.SkusEntity;
import com.example.exception.BaseException;
import com.example.model.page.PageData;
import com.example.mybatis.service.impl.CrudServiceImpl;
import com.example.dao.DishesDao;
import com.example.entity.DishesEntity;
import com.example.service.*;
import com.example.utils.ConvertUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 菜品表
 *
 * @author yyyyjinying 1020066395@qq.com
 * @since 1.0-SNAPSHOT 2025-04-29
 */
@Service
public class DishesServiceImpl extends CrudServiceImpl<DishesDao, DishesEntity, DishesDTO> implements DishesService {

    @Autowired
    private TagsService tagsService;

    @Autowired
    private FlavorsService flavorsService;

    @Autowired
    private ImagesDao imagesDao;

    @Autowired
    private ImagesService imagesService;

    @Autowired
    private SkusService skusService;

    @Autowired
    private RawMaterialsConfigService rawMaterialsConfigService;

    @Override
    public QueryWrapper<DishesEntity> getWrapper(Map<String, Object> params) {
        QueryWrapper<DishesEntity> wrapper = new QueryWrapper<>();

        String name = (String) params.get("name");
        wrapper.eq(StringUtils.isNotBlank(name), "name", name);

        return wrapper;
    }


    @Override
    public DishesDTO detailsByDishId(Long dishId) {
        // 参数校验
        if (dishId == null) {
            throw new BaseException("dishId cannot be null");
        }

        DishesDTO dishesDTO = null;
        try {
            DishesEntity dishesEntitie = baseDao.selectById(dishId);
            dishesDTO = ConvertUtils.sourceToTarget(dishesEntitie, DishesDTO.class);

            LambdaQueryWrapper<ImagesEntity> queryImages = new LambdaQueryWrapper<ImagesEntity>().in(ImagesEntity::getImageBelong, ListUtil.of(0, 7)).eq(ImagesEntity::getBelongId, dishId).eq(ImagesEntity::getIsDelete, 0);
            List<ImagesEntity> imagesEntities = imagesDao.selectList(queryImages);
            List<ImagesDTO> imageLists = ConvertUtils.sourceToTarget(imagesEntities, ImagesDTO.class);
            List<ImagesDTO> collect1 = imageLists.stream().filter(item -> item.getImageBelong().equals(0)).collect(Collectors.toList());
            List<ImagesDTO> collect2 = imageLists.stream().filter(item -> item.getImageBelong().equals(7)).collect(Collectors.toList());
            // 设置大图
            dishesDTO.setImageLists(collect1);
            // 设置缩略图
            dishesDTO.setThumbnailLists(collect2);

            // 获取标签
            List<TagsDTO> tagsDTOS = tagsService.tagByDishId(dishId);
            dishesDTO.setTagLists(tagsDTOS);
            // 获取口味
            List<DishFlavorsDTO> flavorsDTOS = flavorsService.flavorsByDishId(dishId);
            dishesDTO.setFlavorLists(flavorsDTOS);

            // 获取sku
            List<SkusEntity> queryskus = skusService.queryskus(dishId);
            dishesDTO.setSkuLists(ConvertUtils.sourceToTarget(queryskus, SkusDTO.class));

            // 物料
            List<RawMaterialsConfigDTO> materialQuery = rawMaterialsConfigService.query(dishId);
            dishesDTO.setMaterialLists(materialQuery);

        } catch (Exception e) {
            throw new BaseException(e.getMessage());
        }

        return dishesDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DishesDTO dto) {
        dto.setDishId(snowflake.nextId());
        // 保存图片
        Map<String, String> stringStringMap = imagesService.saveUpdateImages(dto.getDishId(), dto.getImageLists(), dto.getThumbnailLists());
        dto.setImageUrl(stringStringMap.get("imageUrl"));
        dto.setThumbnailUrl(stringStringMap.get("thumbnailUrl"));
        super.save(dto);
        // 保存标签
        List<TagsDTO> tagLists = dto.getTagLists();
        tagsService.saveAndUpdateTag(dto.getDishId(), tagLists);
        // 保存口味
        List<DishFlavorsDTO> flavorLists = dto.getFlavorLists();
        flavorsService.saveAndUpdateFlavor(dto.getDishId(), flavorLists);

        // 保存sku
        List<SkusDTO> skuLists = dto.getSkuLists();
        List<SkusEntity> skus = skuLists.stream().filter(item -> ObjectUtil.isEmpty(item.getSkuId())).map(item -> {
            SkusEntity skusEntity = ConvertUtils.sourceToTarget(item, SkusEntity.class);
            skusEntity.setDishId(dto.getDishId());
            return skusEntity;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(skus)){
            skusService.insertBatch(skus);
        }
        // 物料
        List<RawMaterialsConfigEntity> materialList = dto.getMaterialLists().stream().filter(item -> ObjectUtil.isEmpty(item.getConfigId())).map(item -> {
            RawMaterialsConfigEntity rawMaterialsConfigEntity = ConvertUtils.sourceToTarget(item, RawMaterialsConfigEntity.class);
            rawMaterialsConfigEntity.setDishId(dto.getDishId());
            return rawMaterialsConfigEntity;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(materialList)){
            rawMaterialsConfigService.insertBatch(materialList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DishesDTO dto) {

        // 保存图片
        Map<String, String> stringStringMap = imagesService.saveUpdateImages(dto.getDishId(), dto.getImageLists(), dto.getThumbnailLists());
        dto.setImageUrl(stringStringMap.get("imageUrl"));
        dto.setThumbnailUrl(stringStringMap.get("thumbnailUrl"));

        DishesEntity dishesEntity = ConvertUtils.sourceToTarget(dto, DishesEntity.class);
        super.updateById(dishesEntity);

        List<TagsDTO> tagLists = dto.getTagLists();
        tagsService.saveAndUpdateTag(dto.getDishId(), tagLists);

        List<DishFlavorsDTO> flavorLists = dto.getFlavorLists();
        flavorsService.saveAndUpdateFlavor(dto.getDishId(), flavorLists);

        // 保存sku
        List<SkusDTO> skuLists = dto.getSkuLists();
        List<Long> skuIds = skuLists.stream().filter(item -> ObjectUtil.isNotEmpty(item.getSkuId())).map(SkusDTO::getSkuId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(skuIds)) {
            skusService.deleteSkus(skuIds, dto.getDishId());
        }
        List<SkusDTO> updateSkuLists = skuLists.stream().filter(item -> ObjectUtil.isNotEmpty(item.getSkuId())).collect(Collectors.toList());
        List<SkusDTO> insertSkuLists = skuLists.stream().filter(item -> ObjectUtil.isEmpty(item.getSkuId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(updateSkuLists)) {
            skusService.updateBatchById(ConvertUtils.sourceToTarget(updateSkuLists, SkusEntity.class));
        }
        if (CollectionUtils.isNotEmpty(insertSkuLists)) {
            skusService.insertBatch(ConvertUtils.sourceToTarget(insertSkuLists, SkusEntity.class));
        }

        // 保存sku
        List<RawMaterialsConfigDTO> materialLists = dto.getMaterialLists();
        List<Long> configId = materialLists.stream().filter(item -> ObjectUtil.isNotEmpty(item.getConfigId())).map(RawMaterialsConfigDTO::getConfigId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(configId)) {
            rawMaterialsConfigService.deleteMaterials(configId, dto.getDishId());
        }
        List<RawMaterialsConfigDTO> updateLists = materialLists.stream().filter(item -> ObjectUtil.isNotEmpty(item.getConfigId())).collect(Collectors.toList());
        List<RawMaterialsConfigDTO> insertLists = materialLists.stream().filter(item -> ObjectUtil.isEmpty(item.getConfigId())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(updateLists)) {
            rawMaterialsConfigService.updateBatchById(ConvertUtils.sourceToTarget(updateLists, RawMaterialsConfigEntity.class));
        }
        if (CollectionUtils.isNotEmpty(insertLists)) {
            rawMaterialsConfigService.insertBatch(ConvertUtils.sourceToTarget(insertLists, RawMaterialsConfigEntity.class));
        }

    }

    @Override
    public void delete(Long[] ids) {
        super.delete(ids);
        baseDao.deleteDishTagRelation(List.of(ids));
        baseDao.deleteDishFlavorsRelation(List.of(ids));
        baseDao.deleteDishSkus(List.of(ids));
        baseDao.deleteDishMaterials(List.of(ids));

        // 逻辑删除图片列表
        imagesService.deleteAllByBelongId(List.of(ids));
    }

    @Override
    public PageData<DishesDTO> page(Map<String, Object> params) {
        IPage<DishesEntity> page = getPage(params, "update_date", false);
        List<DishesEntity> dishesEntities = baseDao.getPage(params);
        page.setRecords(dishesEntities);
        return getPageData(page, DishesDTO.class);
    }


}